const app = getApp()
var utilMd5 = require('../../utils/md5.js');
var utilSign = require('../../utils/sign.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    mobile: '',
    pwd: '',
    isIpx: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    app.globalData.timespan= utilSign.getTimestamp();
    app.globalData.appKey=utilSign.sign( app.globalData.key, app.globalData.timespan);
    var windowWidth = wx.getSystemInfoSync().windowWidth;
    var windowHeight = wx.getSystemInfoSync().windowHeight;
    var username_height = 750 * windowHeight / windowWidth;
    var that = this
    wx.getSystemInfo({
      success: function(res) {
        let model = res.model.substring(0, res.model.indexOf("X")) + "X";
        console.log(model);
        if (model == 'iPhone X') {
          that.setData({
            isIpx: true
          })
        }
      }
    })
    var mobile = wx.getStorageSync('mobile'); //存储用户名
    var pwd = wx.getStorageSync('pwd'); //存储密码
     this.setData({
       mobile: mobile,
       pwd:pwd
    })
    console.log('mobile' + mobile);
    console.log(pwd);



    if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        app.globalData.userInfo = res.userInfo
        console.log("去登录1")
        console.log(res)
        var that = this;
        wx.login({
          success: function (res) {
            if (res.code) {
              app.globalData.wxcode = res.code
              that.login();

            } else {
              console.log('获取用户登录态失败！' + res.errMsg)
            }
          }
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          console.log("去登录2")
          console.log(res)
          var that = this;
          wx.login({
            success: function (res) {
              if (res.code) {
                app.globalData.wxcode = res.code
                that.login();
  
              } else {
                console.log('获取用户登录态失败！' + res.errMsg)
              }
            }
          })
        }
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },


  login: function () {
    var that = this;
    if (this.data.mobile && this.data.pwd) {
      wx.showNavigationBarLoading() //在当前页面显示导航条加载动画
      wx.showLoading({ //显示 loading 提示框
        title: "正在登录...",
      })
      var that = this;
      console.log(this.data.mobile);
      console.log(this.data.pwd);
      var data = {
        "username": this.data.mobile,
        "password": this.data.pwd,
        "addDevice": 0,
        "appType": app.globalData.appType,
        "version": "1.0",
        "appKey": app.globalData.appKey,
        "mobileType": app.globalData.mobileType,
        "timeSpan": app.globalData.timespan,
        "mobileSerialnumber": "",
        "mobileInfo": "",
        "wxcode": app.globalData.wxcode,
        "wxNickName": encodeURIComponent(app.globalData.userInfo.nickName),
        "avatarUrl":app.globalData.userInfo.avatarUrl
      }
      wx.request({
        url: app.globalData.serverUrl,
        data: {
          "data": JSON.stringify(data),
          'act': "login"
        },
        method: 'POST',
        header: {
          'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
        },
        success: function (res) {
          console.log(res);
          wx.hideNavigationBarLoading()
          wx.hideLoading()
          if (res.data.status == 0) { 
            wx.setStorageSync('mobile', that.data.mobile); //存储用户名
            wx.setStorageSync('pwd', that.data.pwd); //存储密码 
            if (res.data.info.schoollist == null || res.data.info.schoollist.length == 0) {
              wx.showToast({
                title: "没有学校信息",
                icon: 'none',
                duration: 2000,
                mask: true
              })
              return;

            } else {

              //保存设置信息
              wx.setStorageSync('NationalName', res.data.info.NationalName);
              wx.setStorageSync('age', res.data.info.age);
              wx.setStorageSync('duty', res.data.info.duty);
              wx.setStorageSync('name', res.data.info.name);
              wx.setStorageSync('photo', res.data.info.photo);
              wx.setStorageSync('sex', res.data.info.sex);
              wx.setStorageSync('userid', res.data.info.userid);
              wx.setStorageSync('familyId', res.data.familyId);
              wx.setStorageSync('schoollist', res.data.info.schoollist);
              wx.setStorageSync('schoolRole', res.data.info.schoolRole); // 1-集团园    2-集团园下属子园   3-独立园所
              if (res.data.info.sex == 0) {
                wx.setStorageSync('sex', "女");
              } else {
                wx.setStorageSync('sex', "男");
              }
              app.globalData.islogin = true;
              app.globalData.schoolRole = res.data.schoolRole
              app.globalData.name = res.data.info.name;
              app.globalData.photo = res.data.info.photo;
              app.globalData.userId = res.data.info.userid;
              app.globalData.familyId=res.data.familyId;
              app.globalData.schoolId = res.data.info.schoollist[0].schoolID;
              var pages = getCurrentPages();
              var currPage = pages[pages.length - 1]; //当前页面
              var prevPage = pages[pages.length - 2];
              wx.switchTab({
                url: '../index/index',
              })
            }
            

          } else if (res.data.status == -2) {
            wx.showToast({
              title: "账号信息不存在",
              icon: 'none',
              duration: 2000,
              mask: true
            })
          } else if (res.data.status == -6) { //请联系园所解除原绑定
            wx.showToast({
              title: "您的账号存在风险，已停止使用，请尽快联系园所！",
              icon: 'none',
              duration: 2000,
              mask: true
            })
          } else if (res.data.status == -7) { //请发送短信更换设备在登录界面如果返回states是-7，跳转到获取验证码界面，点击获取验证码按钮获取验证码，输入正确验证码之后重新走登录接口，并添加新参数@"addDevice”:@“1”，登录成功进入首页；
            wx.showToast({
              title: "您的账号存在风险，已停止使用，请尽快联系园所！",
              icon: 'none',
              duration: 2000,
              mask: true
            })
          } else if (res.data.status == -8) { //两台设备被冻结
            wx.showToast({
              title: "您的账号存在风险，已停止使用，请尽快联系园所！",
              icon: 'none',
              duration: 2000,
              mask: true
            })
          } else if (res.data.status == -9) { //设备被冻结
            wx.showToast({
              title: "您的账号存在风险，已停止使用，请尽快联系园所！",
              icon: 'none',
              duration: 2000,
              mask: true
            })
          } else if (res.data.status == -10) { //设备认证失败
            wx.showToast({
              title: "您的账号存在风险，已停止使用，请尽快联系园所！",
              icon: 'none',
              duration: 2000,
              mask: true
            })
          }else if (res.data.status == -14) { //账号已被其他账户绑定，请退出
            wx.showModal({
              title: '提示',
              content: res.data.msg,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            })
          } else {
            wx.showToast({
              title: "用户名或密码错误",
              icon: 'none',
              duration: 2000,
              mask: true
            })
            console.log(res.data.msg);
          }
        },
        fail: function (res) {
          wx.hideNavigationBarLoading()
          wx.hideLoading()
          wx.showToast({
            title: "登录失败",
            icon: 'none',
            duration: 2000,
            mask: true
          })
          console.log('submit fail');
        },
        complete: function (res) {
          // wx.hideNavigationBarLoading()
          // wx.hideLoading()
          console.log('submit complete');
        }
      })
    }
  },

  btnClick: function() {
    wx.redirectTo({
      url: '../login/login',
    })
  },

  getUserInfo: function(e) {
    
    console.log(e)
    if(!(e.detail.errMsg=="getUserInfo:fail auth deny")){
      console.log("去登录")
      app.globalData.userInfo = e.detail.userInfo
      wx.redirectTo({
        url: '../login/login',
      })
      
    }
    else{
      console.log("拒绝授权")
    }
    
  }

})